package first.group.ssh.packet.reader;

import first.group.ssh.packet.PacketParser;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;

public class StringReader {
    public static String readString(ByteBuffer buffer) {
        if (!PacketParser.bufferRemains(buffer, 4)) {
            return null;
        }
        var len = buffer.getInt();
        if (!PacketParser.bufferRemains(buffer, len)) {
            return null;
        }
        
        var origLimit = buffer.limit();
        buffer.limit(buffer.position() + len);
        CharBuffer chars = StandardCharsets.UTF_8.decode(buffer);
        buffer.limit(origLimit);
        
        String str = chars.toString();
        return str;
    }
    
    public static boolean readByteBuffer(ByteBuffer buffer, ByteBuffer out) {
        if (!PacketParser.bufferRemains(buffer, 4)) {
            return false;
        }
        var len = buffer.getInt();
        if (!PacketParser.bufferRemains(buffer, len)) {
            return false;
        }
        
        var origLimit = buffer.limit();
        buffer.limit(buffer.position() + len);
        out.put(buffer);
        buffer.limit(origLimit);
        
        return true;
    }
    
    public static byte[] readByteArray(ByteBuffer buffer) {
        if (!PacketParser.bufferRemains(buffer, 4)) {
            return null;
        }
        var len = buffer.getInt();
        if (!PacketParser.bufferRemains(buffer, len)) {
            return null;
        }
        
        var origLimit = buffer.limit();
        buffer.limit(buffer.position() + len);
        byte[] arr = new byte[len];
        buffer.get(arr);
        buffer.limit(origLimit);
        
        return arr;
    }
}
